package javax.core.storage.spring.s3;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.core.storage.entity.FileStorageDO;
import javax.core.storage.entity.SaveResultDO;
import javax.core.storage.service.FileStorageService;
import javax.core.storage.utils.FileStorageUtil;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;

@Component("awsS3")
public class FileStorageServiceAmazonS3Impl implements FileStorageService {
    @Value("${file.storage.aws.host}")
    private String host;

    @Autowired
    private AWSClientS3 awsClientS3;

    @Override
    public FileStorageDO getOneFileById(Long id) {
        return null;
    }

    @Override
    public File getFileByXpath(String xpath) {
        return null;
    }

    @Override
    public SaveResultDO saveFile(FileStorageDO fileStorage, InputStream fileInputStream) {
        try {
            BufferedInputStream attachmentFile = new BufferedInputStream(fileInputStream);
            attachmentFile.mark(24 * 1024 * 1024);
            String fileMD5 = FileStorageUtil.getMD5(attachmentFile, false);
            attachmentFile.reset();

            String xpath = FileStorageUtil.toStoragePathByMD5(fileMD5, fileStorage.getFileName());
            awsClientS3.savePublicObject(fileStorage.getBucket(), xpath,
                    attachmentFile);

            String fileUrl = String.format("https://" + host + "/%s/%s", fileStorage.getBucket(), xpath);
            return SaveResultDO.ok(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return SaveResultDO.err(e.getMessage());
        }
    }
}
